package demo.shiro.service.impl;

import demo.shiro.entity.User;
import demo.shiro.service.UserService;
import java.util.Map;
import org.smart4j.framework.dao.DataSet;
import org.smart4j.framework.tx.annotation.Service;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.security.SmartSecurityHelper;
import org.smart4j.security.exception.LoginException;
import org.smart4j.security.exception.RegisterException;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public void login(String username, String password, boolean isRememberMe) throws LoginException {
        SmartSecurityHelper.login(username, password, isRememberMe);
    }

    @Override
    public void register(Map<String, Object> fieldMap) throws RegisterException {
        // 获取表单数据
        String username = CastUtil.castString(fieldMap.get("username"));
        String password = CastUtil.castString(fieldMap.get("password"));

        // 在 user 表中根据 username 查询用户是否已存在
        Long userCount = DataSet.selectCount(User.class, "username = ?", username);
        if (userCount > 0) {
            throw new RegisterException();
        }

        // 加密密码
        password = SmartSecurityHelper.encrypt(password);

        // 插入 user 表
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        DataSet.insert(user);
    }
}
